package com.bestcem.xm.label.dao.impl.mysql;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.PageUtil;
import com.bestcem.xm.common.core.uitls.DateUtil;
import com.bestcem.xm.common.core.uitls.StringUtil;
import com.bestcem.xm.label.constant.Constants;
import com.bestcem.xm.label.dao.BaseDao;
import com.bestcem.xm.label.dao.LabelValueDao;
import com.bestcem.xm.label.dao.mapper.LabelValueMapper;
import com.bestcem.xm.label.entity.mongo.LabelValue;
import com.bestcem.xm.label.entity.mysql.LabelValueEntity;
import com.bestcem.xm.label.entity.pojo.LabelGroupDO;
import com.bestcem.xm.label.entity.pojo.LabelValueDO;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 标签值数据访问层
 *
 * @author ming.xue <ming.xue@idiaoyan.com>
 * @date 2021-05-19
 */
@Repository("labelValueDao")
public class LabelValueDaoImpl extends BaseDao implements LabelValueDao {

    @Resource
    private LabelValueMapper labelValueMapper;

    @Override
    public List<LabelValueDO> listByOrgIdAndAuto(String orgId, Boolean auto) {
        Integer autoValue = null;
        if (Objects.nonNull(auto)) {
            autoValue = auto ? 1 : 0;
        }

        // 符合条件的标签值 总数
        Integer count = labelValueMapper.countByOrgIdAndAuto(orgId, autoValue);

        // 分批查找
        int pageNum = Constants.ZERO;
        List<LabelValueDO> values = new ArrayList<>(count);

        while (pageNum * Constants.LABEL_VALUE_PAGE_SIZE < count) {
            int start = PageUtil.getStart(pageNum, Constants.LABEL_VALUE_PAGE_SIZE);
            List<LabelValueEntity> entities = labelValueMapper.findByOrgIdAndAuto(orgId, autoValue, start,  Constants.LABEL_VALUE_PAGE_SIZE);
            if (CollUtil.isNotEmpty(entities)) {
                values.addAll(entities.stream().map(LabelValueDO::toDo).collect(Collectors.toList()));
            }
            pageNum++;
        }

        return values;
    }

    /**
     * 获取标签值列表
     *
     * @param orgId
     * @param labelId
     * @param auto
     * @return
     */
    @Override
    public List<LabelValueDO> listByOrgIdAndLabelIdAndAuto(String orgId, String labelId, Boolean auto) {
        Integer autoValue = null;
        if (Objects.nonNull(auto)) {
            autoValue = auto ? 1 : 0;
        }

        List<LabelValueEntity> entities = labelValueMapper.findByOrgIdAndLabelIdAndAuto(orgId, labelId, autoValue);
        if (CollectionUtils.isEmpty(entities)) {
            return Collections.emptyList();
        }
        return entities.stream().map(LabelValueDO::toDo).collect(Collectors.toList());
    }

    @Override
    public List<LabelValueDO> listByLabelId(String labelId) {
        List<LabelValueEntity> entities = labelValueMapper.findByLabelId(labelId);
        if (CollUtil.isNotEmpty(entities)) {
            return entities.stream().map(LabelValueDO::toDo).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public void saveBatch(List<LabelValueDO> labelValues) {
        if (CollectionUtil.isEmpty(labelValues)) {
            return;
        }

        // 插入+返回
        List<LabelValueDO> result = new ArrayList<>();
        for (LabelValueDO labelValue : labelValues) {
            labelValue.setLabelValueId(StringUtil.getId());
            labelValueMapper.createLabelValue(LabelValueDO.toEntity(labelValue));
//            LabelValueEntity entity = labelValueMapper.findById(labelValue.getLabelValueId());
//            result.add(LabelValueDO.toDo(entity));
        }
        // return result;
    }

    @Override
    public List<LabelValueDO> listByLabelIdAndValue(String labelId, String value) {
        List<LabelValueEntity> entities = labelValueMapper.findByValueAndLabelId(value, labelId);
        if (CollUtil.isNotEmpty(entities)) {
            entities.stream().map(entity -> LabelValueDO.toDo(entity)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public Integer countByLabelId(String labelId) {
        return labelValueMapper.countByLabelId(labelId);
    }

    @Override
    public Boolean deleteByIds(List<String> labelValueIds) {
        labelValueMapper.deleteByIds(labelValueIds);
        return true;
    }

    @Override
    public Boolean deleteByLabelGroupId(String labelGroupId) {
        labelValueMapper.deleteByLabelGroupId(labelGroupId);
        return true;
    }


    @Override
    public Boolean updateSerialByParam(Integer seq, String id, Date updateTime) {
        labelValueMapper.updateSeqById(seq, id, updateTime);
        return true;
    }


    @Override
    public Boolean updateLabelGroupInfo(LabelGroupDO labelGroupDO) {
        // labelValueMapper.updateLabelGroupNameByLabelGroupId(labelGroupDO.getName(), labelGroupDO.getId(), labelGroupDO.getUpdateTime());
        labelValueMapper.updateLabelGroupNameByLabelGroupIdAndOrgId(labelGroupDO.getName(), labelGroupDO.getId(), labelGroupDO.getOrgId(), labelGroupDO.getUpdateTime());
        return true;
    }


    @Override
    public List<LabelValueDO> listByIds(List<String> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<LabelValueEntity> entities = labelValueMapper.findByIds(ids);
        if (CollUtil.isNotEmpty(entities)) {
            return entities.stream().map(entity -> LabelValueDO.toDo(entity)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }


    @Override
    public List<LabelValueDO> listByOrgIdAndAttributeAndIds(String orgId, Integer memberType, List<String> ids) {
        List<LabelValueEntity> entities = labelValueMapper.findByIds(ids);
        if (CollUtil.isNotEmpty(entities)) {
            return entities.stream().map(entity -> LabelValueDO.toDo(entity)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }


    @Override
    public List<LabelValueDO> listByOrgIdAndMemberType(String orgId, Integer memberType) {
        List<LabelValueEntity> entities = labelValueMapper.findByOrgIdAndMemberType(orgId, memberType);
        if (CollUtil.isNotEmpty(entities)) {
            return entities.stream().map(entity -> LabelValueDO.toDo(entity)).collect(Collectors.toList());
        }
        return new ArrayList<LabelValueDO>();
    }


    @Override
    public List<LabelValueDO> listByOrgIdAndMemberTypeSortBySerial(String orgId, Integer memberType) {
        List<LabelValueEntity> entities = labelValueMapper.findByOrgIdAndMemberTypeSortBySerial(orgId, memberType);
        if (CollUtil.isNotEmpty(entities)) {
            return entities.stream().map(entity -> LabelValueDO.toDo(entity)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public void insertOrReplace(LabelValueDO labelValue) {
        LabelValueEntity entity = labelValueMapper.findByValueAndLabelGroupIdAndLabelId(labelValue.getValue(), labelValue.getLabelGroupId(), labelValue.getLabelId());
        if (entity != null) {
            labelValue.setLabelValueId(entity.getLabelValueId());
            // 更新
            labelValue.setUpdateTime(DateUtil.getCommonDate());
            labelValueMapper.update(LabelValueDO.toEntity(labelValue));
        } else {
            labelValue.setLabelValueId(StringUtil.getId());
            labelValue.setCreateTime(DateUtil.getCommonDate());
            labelValue.setUpdateTime(labelValue.getCreateTime());
            labelValueMapper.createLabelValue(LabelValueDO.toEntity(labelValue));
        }
    }

    @Override
    public Boolean updateLabelInfo(LabelValueDO labelValueDO) {
        labelValueMapper.updateLabelInfo(LabelValueDO.toEntity(labelValueDO));
        return true;
    }

    @Override
    public Boolean batchUpdateLabelValue(List<LabelValueDO> updateValues) {
        for (LabelValueDO updateValue : updateValues) {
            labelValueMapper.updateLabelValue(LabelValueDO.toEntity(updateValue));
        }
        return true;
    }

    @Override
    public void batchSaveSampleData(List<LabelValueDO> newLabelValueList) {
        if (CollUtil.isNotEmpty(newLabelValueList)) {
            List<LabelValueEntity> labelValueEntities =
                    newLabelValueList.stream().map(LabelValueDO::toEntity).collect(Collectors.toList());
            labelValueMapper.batchSaveSampleData(labelValueEntities);
        }
    }

    @Override
    public Integer countByOrgIdAndLabelId(String orgId, String labelId) {
        return labelValueMapper.countByOrgIdAndLabelId(orgId, labelId);
    }

    @Override
    public void deleteByOrgIdAndLabelId(String orgId, String labelId) {
        labelValueMapper.deleteByOrgIdAndLabelId(orgId, labelId);
    }

    /**
     * 统计标签值
     *
     * @param ids
     * @return
     */
    @Override
    public long countByIds(Set<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return 0;
        }
        return labelValueMapper.countByIds(ids);
    }

    @Override
    public List<LabelValueDO> findByLabelIds(String orgId, List<String> labelIds) {
        List<LabelValueEntity> entities = labelValueMapper.findByLabelIdsAndOrgId(orgId, labelIds);
        if (CollUtil.isNotEmpty(entities)) {
            return entities.stream().map(entity -> LabelValueDO.toDo(entity)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public void batchDeleteByLabelIds(String orgId, int memberType, List<String> deleteValuesLabelIds) {
        labelValueMapper.batchDeleteByLabelIds(orgId, memberType, deleteValuesLabelIds);
    }

    @Override
    public void batchSave(List<LabelValueDO> allInsertValues) {
        if (CollUtil.isNotEmpty(allInsertValues)) {
            List<LabelValueEntity> labelValueEntities = allInsertValues.stream().map(item -> {
                item.setLabelValueId(StringUtil.getId());
                return LabelValueDO.toEntity(item);
            }).collect(Collectors.toList());
            labelValueMapper.batchSave(labelValueEntities);
        }
    }

    @Override
    public List<LabelValueDO> listBySamplePaging(long offset, int limit) {
        List<LabelValueEntity> entities = labelValueMapper.findBySamplePaging(offset, limit);
        if (CollUtil.isNotEmpty(entities)) {
            return entities.stream().map(entity -> LabelValueDO.toDo(entity)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public void updateCondition(LabelValueDO labelValue) {
         labelValueMapper.update(LabelValueDO.toEntity(labelValue));
    }

    private LabelValueEntity convert(LabelValue labelGroup){
        LabelValueEntity entity = new LabelValueEntity();
        entity.setLabelValueId(labelGroup.getId());
        if(labelGroup.getOrgId().equals("123")){
            return null;
        }
        entity.setOrgId(labelGroup.getOrgId());
        entity.setValue(labelGroup.getValue());
        entity.setMemberType(labelGroup.getAttribute());
        entity.setSeq(labelGroup.getSerial());

        entity.setLabelGroupId(labelGroup.getLabelGroupId());
        entity.setLabelGroupName(labelGroup.getLabelGroupName());
        entity.setLabelId(labelGroup.getLabelId());
        entity.setLabelName(labelGroup.getLabelName());
        entity.setCondition(labelGroup.getCondition());
        entity.setAuto(labelGroup.getAuto() ? 1 : 0);
        entity.setManual(labelGroup.getManual() ? 1 : 0);

        entity.setCreateTime(labelGroup.getCreateTime());
        entity.setUpdateTime(labelGroup.getUpdateTime());
        return entity;
    }
}
